package cn.ddiancan.xddcloud.ddccore.validator;

import java.text.SimpleDateFormat;
import java.util.Date;

import cn.ddiancan.xddcloud.ddccore.validator.annotation.ValidDate;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

public class DateValidator implements ConstraintValidator<ValidDate, Date> {

    private String dateFormat;

    private boolean allowNull;

    @Override
    public void initialize(ValidDate constraintAnnotation) {
        this.dateFormat = constraintAnnotation.format();
        this.allowNull = constraintAnnotation.allowNull();
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(Date value, ConstraintValidatorContext context) {
        if (value == null && allowNull) {
            return true;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
            sdf.setLenient(false);
            sdf.format(value);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
